import React, {useEffect} from 'react';
import {Text, StyleSheet} from 'react-native';
import {
  Button,
  Checkbox,
  Flex,
  Toast,
  Tabs,
  Card,
  Badge,
} from '@ant-design/react-native';
import {LoadingContainer} from '@/rcomponents/Container';
import {formatDate} from '@/helpers/dateutil';
import FlexTextField from '@/rcomponents/flexTextField';
import UserStore from '@/stores/userStore';
import PowerupStore from './powerupStore';

const styles = StyleSheet.create({
  pwCardTitle: {
    fontWeight: 'bold',
  },
});

function PowerupCard({item, checkable, onCheck}) {
  console.log(item);
  return (
    <Card>
      <Card.Header
        title={
          <Text style={styles.pwCardTitle}>
            {item.airplane_no} {item.flight_no}
          </Text>
        }
        extra={
          checkable ? (
            <Checkbox
              checked={item.checked}
              onChange={(event) => onCheck(item.id, event.target.checked)}
            />
          ) : null
        }
      />
      <Card.Body>
        <Flex>
          <FlexTextField
            label="预计起飞时间"
            fieldValue={formatDate(item.est_depart_date, 'YYYY-MM-DD HH:mm')}
          />
        </Flex>
        <Flex>
          <FlexTextField label="放行人员" fieldValue={item.release_by} />
          <FlexTextField label="工作者" fieldValue={item.workers} />
        </Flex>
        <Flex>
          <FlexTextField label="状态" fieldValue={item.statusDes} />
        </Flex>
        {item.status !== 1 && (
          <Flex>
            <FlexTextField
              label="确认信息"
              fieldValue={`${item.operPer}  ${formatDate(
                item.operTime,
                'YYYY-MM-DD HH:mm',
              )}`}
            />
          </Flex>
        )}
        <Flex>
          <FlexTextField label="前序航班" fieldValue={item.preflight} />
          <FlexTextField label="站点" fieldValue={item.airport} />
          <FlexTextField label="后序航班" fieldValue={item.postflight} />
        </Flex>
      </Card.Body>
    </Card>
  );
}

function PowerupTaskList() {
  const pwuStore = PowerupStore.useStore();
  const userStore = UserStore.useStore();
  useEffect(() => {
    handleLoad();
  }, []);
  const handleLoad = () => {
    pwuStore.getPuTasks(userStore.user.LoginName);
  };
  const handleTaskCheck = (taskKey, checked) => {
    pwuStore.checkUnconfrimTask(taskKey, checked);
  };
  const tabbarItems = [
    {
      key: 'unconfirmed',
      title: '待确认',
      dataSource: pwuStore.pwuUnConfirmTasks,
    },
    {
      key: 'confirmed',
      title: '已确认',
      dataSource: pwuStore.pwuConfirmTasks,
    },
  ];
  const handleLongPowerConfirm = async () => {
    const res = await pwuStore.confirmLongPowerItems(userStore.user.LoginName);
    if (res.errorCode) {
      Toast.fail({
        content: res.errorMsg,
      });
    } else {
      Toast.success({
        content: '确认成功',
      });
    }
  };
  const renderTabChild = (tab, index) => {
    const {dataSource} = tabbarItems[index];
    let checkable = false;
    let onCheckHandler = null;
    let longpowerBtn = null;
    if (index === 0) {
      checkable = true;
      onCheckHandler = handleTaskCheck;
      if (dataSource.filter((ds) => ds.checked).length > 0) {
        longpowerBtn = (
          <Flex>
            <Flex.Item>
              <Button
                loading={pwuStore.confirmLongPowerItems.loading}
                type="primary"
                onPress={handleLongPowerConfirm}>
                上电确认
              </Button>
            </Flex.Item>
          </Flex>
        );
      }
    }
    return (
      <>
        <LoadingContainer
          loading={pwuStore.getPuTasks.loading}
          onRefresh={handleLoad}
          data={dataSource}
          renderItem={({item}) => (
            <PowerupCard
              item={item}
              key={item.id}
              checkable={checkable}
              onCheck={onCheckHandler}
            />
          )}
        />
        {longpowerBtn}
      </>
    );
  };
  return (
    <Tabs
      tabs={tabbarItems.map((tbi) => ({
        title: (
          <Badge text={tbi.dataSource.length}>
            <Text>{tbi.title}</Text>
          </Badge>
        ),
      }))}>
      {renderTabChild}
    </Tabs>
  );
}

PowerupTaskList.routeName = 'PowerupTasks';
PowerupTaskList.permission = 'RPowerupTasks';
export default PowerupTaskList;
